﻿using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using ZYCommon;

namespace TextEditor
{
  

    public class ZYKBBuffer
    {
        private bool bolEnableKBSection = true;
        private bool bolLoading = false;
        public static string Custom_KBITEM_SQL = null;
        public static string Custom_KBLIST_SQL = null;
        public static TreeView TrvSelectKBList = new TreeView();
        public bool DesignMode = false;
        private ArrayList myAllKBList = new ArrayList();
        private ZYDBConnection myConn = null;
        private static ZYKBBuffer myInstance = new ZYKBBuffer();
        private ArrayList myKBSectionList = new ArrayList();
        private KB_List myRootList = new KB_List();
        private ArrayList myTemplateList = new ArrayList();
        public bool OnlyCheckYesNoAttribute = false;
        public string ProjectName;
        public bool SearchTemplateOnly = false;
        public string[] SectionList = null;
        public string SectionSQL = null;
        private string strKeyPreFix = "0";
        private string strOwnerSection = null;

        //把KBList添加到KBList的数组中
        public static void AddToKBListArray(ArrayList myList, KB_List myKBList)
        {
            for (int iCount = 0; iCount < myList.Count; iCount++)
            {
                KB_List kb = (KB_List) myList[iCount];
                if (kb.RefCount < myKBList.RefCount)
                {
                    myList.Insert(iCount, myKBList);
                    return;
                }
            }
            myList.Add(myKBList);
        }

        //把知识点添加到一个XML文件中的根节点下面
        public void AllKBListToXML(XmlElement RootElement)
        {
            XmlDocument myDoc = RootElement.OwnerDocument;
            foreach (KB_List myList in this.myAllKBList)
            {
                if (myList.SEQ != null)
                {
                    XmlElement NewElement = myDoc.CreateElement("list");
                    myList.ToXML(NewElement);//设置NewElement结点元素的属性(包括seq、parent、name......)
                    RootElement.AppendChild(NewElement);//把当前节点添加到根节点下面
                    if ((myList.Items != null) && (myList.Items.Count > 0))
                    {
                        foreach (KB_Item myItem in myList.Items)//具体子项item
                        {
                            NewElement = myDoc.CreateElement("item");
                            myItem.ToXML(NewElement);////设置NewElement结点元素的属性(包括seq、kb、text、value.....)
                            RootElement.AppendChild(NewElement);
                        }
                        continue;
                    }
                }
            }
        }

        
        //把kbseq和section绑定
        public bool BindKBToSection(string KBSEQ, bool bolSet, bool ShowInTree)
        {
            KBSection myRecord = this.FindKBSection(this.strOwnerSection, KBSEQ);
            if (bolSet)
            {
                if (myRecord == null)
                {
                    myRecord = new KBSection();
                    myRecord.OwnerSection = this.strOwnerSection;
                    myRecord.KBSEQ = KBSEQ;
                    myRecord.DataState = DataRowState.Added;
                    myRecord.ShowInTree = ShowInTree;
                    this.myKBSectionList.Add(myRecord);
                    return true;
                }
            }
            else if (myRecord != null)
            {
                if (myRecord.isNewRecord())
                {
                    this.myKBSectionList.Remove(myRecord);
                }
                else
                {
                    myRecord.DataState = DataRowState.Deleted;
                }
                return true;
            }
            return false;
        }

        //kb_list绑定到section
        public bool BindKBToSection(KB_List myRootKB, bool bolSet, bool ShowInTree)
        {
            if (StringCommon.HasContent(this.strOwnerSection) && (myRootKB != null))
            {
                bool bolChange = this.InnerBindKBToSection(myRootKB, bolSet, ShowInTree);
                if (bolSet)
                {
                    for (KB_List myParent = myRootKB.Parent; (myParent != null) && (myParent.SEQ != null); myParent = myParent.Parent)
                    {
                        if (this.BindKBToSection(myParent.SEQ, bolSet, ShowInTree))
                        {
                            bolChange = true;
                        }
                    }
                }
                return bolChange;
            }
            return false;
        }

        public bool CanReadKB()
        {
            return ((!this.bolLoading && (this.myAllKBList != null)) && (this.myAllKBList.Count > 0));
        }

        public void Close()
        {
            this.SaveKBRefCount();
        }

        public ET_Document CreateET_Document(string strObjectID)
        {
            ET_Document NewRecord = new ET_Document();
            NewRecord.ObjectID = strObjectID;
            if (this.myConn.ReadOneRecord(NewRecord))
            {
                return NewRecord;
            }
            return null;
        }

        public int DeleteRecords(int Style, IDbCommand myCmd)
        {
            myCmd.Parameters.Clear();
            switch (Style)
            {
                case 0:
                    myCmd.CommandText = "Delete From KB_List Where KB_SEQ Like '" + this.strKeyPreFix + "%'";
                    break;

                case 1:
                    myCmd.CommandText = "Delete From KB_Item Where KB_SEQ Like '" + this.strKeyPreFix + "%'";
                    break;

                case 2:
                    myCmd.CommandText = "Delete From KBSection Where KB_SEQ Like '" + this.strKeyPreFix + "%'";
                    break;

                case 3:
                    myCmd.CommandText = "Delete From ET_Document Where ObjectID Like '" + this.strKeyPreFix + "%'";
                    break;

                default:
                    return -1;
            }
            return myCmd.ExecuteNonQuery();
        }

        public KBSection FindKBSection(string strSection, string KBSEQ)
        {
            if (StringCommon.HasContent(strSection) && (KBSEQ != null))
            {
                strSection = strSection.Trim();
                foreach (KBSection myRecord in this.myKBSectionList)
                {
                    if ((strSection.Equals(myRecord.OwnerSection) && (myRecord.KBSEQ == KBSEQ)) && !myRecord.isDeleted())
                    {
                        return myRecord;
                    }
                }
            }
            return null;
        }

        public void GetAllChangedRecord(ArrayList myOutList)
        {
            this.InnerGetChangedKB(this.myRootList, myOutList);
            foreach (KBSection myRecord in this.myKBSectionList)
            {
                if (!myRecord.isUnchanged())
                {
                    myOutList.Add(myRecord);
                }
            }
        }

        public int GetAllET_Document(ArrayList myList)
        {
            using (IDbCommand myCmd = this.myConn.CreateCommand())
            {
                myCmd.CommandText = ET_Document.GetSelectSQL() + " Where ObjectID Like '" + this.strKeyPreFix + "%'";
                IDataReader myReader = myCmd.ExecuteReader(CommandBehavior.SingleResult);
                int iCount = 0;
                while (myReader.Read())
                {
                    ET_Document NewDoc = new ET_Document();
                    if (NewDoc.FromReader(myReader, this.myConn))
                    {
                        myList.Add(NewDoc);
                        iCount++;
                    }
                }
                myReader.Close();
                return iCount;
            }
        }

        //返回选项的前景色
        public Color GetItemForeColor(KB_List myList)
        {
            if (myList != null)
            {
                KBSection myKBSection = this.FindKBSection(this.strOwnerSection, myList.SEQ);
                if ((this.bolEnableKBSection && (this.strOwnerSection != null)) && this.DesignMode)
                {
                    if ((myList.SEQ != null) && (myKBSection == null))
                    {
                        return Color.LightCoral;
                    }
                }
                else if ((!myList.InputBoxAttribute && !myList.HasItems()) && (!myList.HasChildren() && StringCommon.isBlankString(myList.ListSQL)))
                {
                    return Color.Blue;
                }
            }
            return SystemColors.WindowText;
        }

        public KB_List GetKBList(string vSEQ)
        {
            if (this.myAllKBList != null)
            {
                foreach (KB_List myList in this.myAllKBList)
                {
                    if (myList.SEQ == vSEQ)
                    {
                        return myList;
                    }
                }
            }
            return null;
        }

        public KB_List GetKBListByName(string strName, bool bolMatchAll)
        {
            if (this.myAllKBList != null)
            {
                foreach (KB_List myList in this.myAllKBList)
                {
                    if (myList.Visible && ((myList.Name == strName) || (!bolMatchAll && (myList.Name.IndexOf(strName) >= 0))))
                    {
                        return myList;
                    }
                }
            }
            return null;
        }

        public bool GetKBListsByName(string strName, ArrayList myOutList, bool bolCompareName)
        {
            if (this.bolLoading)
            {
                return false;
            }
            if (StringCommon.isBlankString(strName))
            {
                myOutList.AddRange(this.myRootList.ChildNodes);
                return false;
            }
            ArrayList myList = new ArrayList();
            ArrayList myTopList = new ArrayList();
            bool bolMatch = false;
            string strSpell = strName.Trim().ToUpper();
            if (!this.SearchTemplateOnly && (this.myAllKBList != null))
            {
                foreach (KB_List myKB in this.myAllKBList)
                {
                    if ((!myKB.Visible || (myKB.SEQ == null)) || (!myKB.HasItems() && ((myKB.ListSQL == null) || (myKB.ListSQL.Length <= 0))))
                    {
                        continue;
                    }
                    if (this.OnlyCheckYesNoAttribute)
                    {
                        if (myKB.YesNoAttribute)
                        {
                            AddToKBListArray(myTopList, myKB);
                        }
                        continue;
                    }
                    if ((bolCompareName && (myKB.Name == strName)) || (myKB.ChineseSpell == strSpell))
                    {
                        AddToKBListArray(myTopList, myKB);
                        bolMatch = true;
                        continue;
                    }
                    if ((bolCompareName && (myKB.Name.IndexOf(strName) >= 0)) || myKB.ChineseSpell.StartsWith(strSpell))
                    {
                        myList.Insert(0, myKB);
                        bolMatch = true;
                        continue;
                    }
                    if (bolCompareName && (strName.IndexOf(myKB.Name) >= 0))
                    {
                        myList.Add(myKB);
                    }
                }
            }
            if (!this.OnlyCheckYesNoAttribute && (this.myTemplateList != null))
            {
                foreach (KB_Item myItem in this.myTemplateList)
                {
                    if (!myItem.OwnerList.Visible)
                    {
                        continue;
                    }
                    string strItemSpell = StringCommon.GetChineseSpell(myItem.ItemText);
                    if ((bolCompareName && (myItem.ItemText == strName)) || (strItemSpell == strSpell))
                    {
                        myTopList.Add(myItem);
                    }
                    else if ((bolCompareName && (myItem.ItemText.IndexOf(strName) >= 0)) || ((strName.IndexOf(myItem.ItemText) >= 0) || strItemSpell.StartsWith(strSpell)))
                    {
                        myList.Insert(0, myItem);
                    }
                    bolMatch = true;
                }
            }
            if (myTopList.Count > 0)
            {
                myOutList.AddRange(myTopList);
            }
            if (myList.Count > 0)
            {
                myOutList.AddRange(myList);
            }
            if (!this.SearchTemplateOnly)
            {
                if (myOutList.Count > 0)
                {
                    myOutList.Add(null);
                }
                foreach (KB_List myList2 in this.myRootList.ChildNodes)
                {
                    if (myList2.Visible)
                    {
                        myOutList.Add(myList2);
                    }
                }
            }
            return bolMatch;
        }

        //得到strSEQ 相当于id增长策略 返回strSEQ
        public string GetSEQString(string strSQL, IDbCommand myCmd)
        {
            string strValue = null;
            myCmd.CommandText = "Select Max(KB_SEQ) From KB_List Where KB_SEQ like '" + this.strKeyPreFix + "%'";
            IDataReader myReader = myCmd.ExecuteReader(CommandBehavior.SingleRow);
            if (myReader.Read() && !myReader.IsDBNull(0))
            {
                strValue = myReader.GetString(0);
            }
            else
            {
                strValue = this.strKeyPreFix + "0000000";
            }
            myReader.Close();
            return strValue;
        }

        public KB_Item GetTemplateByID(int id)
        {
            if (this.myTemplateList != null)
            {
                foreach (KB_Item myItem in this.myTemplateList)
                {
                    if (myItem.ItemSEQ == id)
                    {
                        return myItem;
                    }
                }
            }
            return null;
        }

        public bool GetTemplatesByName(string strName, ArrayList myOutList)
        {
            if (this.bolLoading)
            {
                return false;
            }
            if (StringCommon.isBlankString(strName))
            {
                myOutList.AddRange(this.myTemplateList);
                return false;
            }
            ArrayList myList = new ArrayList();
            ArrayList myTopList = new ArrayList();
            ArrayList myList2 = new ArrayList();
            bool bolMatch = false;
            foreach (KB_Item myItem in this.myTemplateList)
            {
                if (myItem.ItemText == strName)
                {
                    myTopList.Add(myItem);
                    bolMatch = true;
                    continue;
                }
                if ((myItem.ItemText.IndexOf(strName) >= 0) || (strName.IndexOf(myItem.ItemText) >= 0))
                {
                    myList.Add(myItem);
                    bolMatch = true;
                    continue;
                }
                myList2.Add(myItem);
            }
            myOutList.AddRange(myTopList);
            myOutList.AddRange(myList);
            myOutList.AddRange(myList2);
            return bolMatch;
        }

        public bool HasBindKBSection(string strSection, string KBSEQ)
        {
            if ((StringCommon.HasContent(strSection) && (KBSEQ != null)) && (this.myKBSectionList.Count > 0))
            {
                strSection = strSection.Trim();
                foreach (KBSection myRecord in this.myKBSectionList)
                {
                    if ((!myRecord.isDeleted() && strSection.Equals(myRecord.OwnerSection)) && (myRecord.KBSEQ == KBSEQ))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private bool InnerBindKBToSection(KB_List myRootKB, bool bolSet, bool ShowInTree)
        {
            if (StringCommon.HasContent(this.strOwnerSection) && (myRootKB != null))
            {
                bool bolChange = this.BindKBToSection(myRootKB.SEQ, bolSet, ShowInTree);
                if (myRootKB.ChildNodes != null)
                {
                    foreach (KB_List myList in myRootKB.ChildNodes)
                    {
                        if (this.BindKBToSection(myList, bolSet, ShowInTree))
                        {
                            bolChange = true;
                        }
                    }
                }
                return bolChange;
            }
            return false;
        }

        private void InnerGetChangedKB(KB_List myRootKB, ArrayList myOutList)
        {
            if (myRootKB.Items != null)
            {
                foreach (KB_Item myItem in myRootKB.Items)
                {
                    if (!myItem.isUnchanged())
                    {
                        myOutList.Add(myItem);
                    }
                }
            }
            if (myRootKB.ChildNodes != null)
            {
                foreach (KB_List myList in myRootKB.ChildNodes)
                {
                    if (!myList.isUnchanged())
                    {
                        myOutList.Add(myList);
                    }
                    this.InnerGetChangedKB(myList, myOutList);
                }
            }
        }

        public static int KBListFromXML(XmlElement vRootElement, KB_List vRootList)
        {
            int iCount = 0;
            if ((vRootElement != null) && (vRootList != null))
            {
                foreach (XmlNode myNode in vRootElement.ChildNodes)
                {
                    if (myNode.Name == "kb")
                    {
                        if (vRootList.ChildNodes == null)
                        {
                            vRootList.ChildNodes = new ArrayList();
                        }
                        KB_List NewKBList = new KB_List();
                        NewKBList.FromXML(myNode as XmlElement);
                        NewKBList.SEQ = null;
                        NewKBList.Parent = vRootList;
                        vRootList.ChildNodes.Add(NewKBList);
                        iCount++;
                        iCount += KBListFromXML(myNode as XmlElement, NewKBList);
                        continue;
                    }
                    if (myNode.Name == "item")
                    {
                        if (vRootList.Items == null)
                        {
                            vRootList.Items = new ArrayList();
                        }
                        KB_Item NewItem = new KB_Item();
                        NewItem.FromXML(myNode as XmlElement);
                        NewItem.ItemSEQ = -1;
                        NewItem.OwnerList = vRootList;
                        vRootList.Items.Add(NewItem);
                        iCount++;
                    }
                }
                if ((vRootList.ChildNodes != null) && (vRootList.ChildNodes.Count == 0))
                {
                    vRootList.ChildNodes = null;
                }
                if ((vRootList.Items != null) && (vRootList.Items.Count == 0))
                {
                    vRootList.Items = null;
                }
            }
            return iCount;
        }

        public int KBListToObjList(ArrayList myObjList, KB_List vRootList, bool IncludeTemplate, IDbCommand myCmd)
        {
            int iCount = 0;
            if ((myObjList != null) && (vRootList != null))
            {
                if ((vRootList.ChildNodes != null) && (vRootList.ChildNodes.Count > 0))
                {
                    myObjList.AddRange(vRootList.ChildNodes);
                    iCount += vRootList.ChildNodes.Count;
                    foreach (KB_List myList in vRootList.ChildNodes)
                    {
                        iCount += this.KBListToObjList(myObjList, myList, IncludeTemplate, myCmd);
                        if (this.myKBSectionList != null)
                        {
                            foreach (KBSection mySection in this.myKBSectionList)
                            {
                                if (mySection.KBSEQ == myList.SEQ)
                                {
                                    myObjList.Add(mySection);
                                    iCount++;
                                }
                            }
                            continue;
                        }
                    }
                    return iCount;
                }
                if ((vRootList.Items == null) || (vRootList.Items.Count <= 0))
                {
                    return iCount;
                }
                myObjList.AddRange(vRootList.Items);
                iCount += vRootList.Items.Count;
                foreach (KB_Item myItem in vRootList.Items)
                {
                    if ((myItem.isTemplate() && StringCommon.IsInteger(myItem.ItemValue)) && (IncludeTemplate && (myCmd != null)))
                    {
                        try
                        {
                            ET_Document myDoc = new ET_Document();
                            myDoc.SetKeyWord(myItem.ItemValue);
                            myDoc.SetSelectCommandForOneRecord(myCmd, null);
                            IDataReader myReader = myCmd.ExecuteReader(CommandBehavior.SingleRow | CommandBehavior.SingleResult);
                            if (myReader.Read() && myDoc.FromReader(myReader, null))
                            {
                                myObjList.Add(myDoc);
                            }
                            myReader.Close();
                            continue;
                        }
                        catch (Exception ext)
                        {
                            MessageBox.Show(null, "导出模板 " + myItem.ItemText + " 数据错误:\r\n" + ext.ToString() + myCmd.CommandText, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                            continue;
                        }
                    }
                }
            }
            return iCount;
        }

        public int KBListToXML(XmlElement vRootElement, KB_List vRootList, bool IncludeTemplate, IDbCommand myCmd)
        {
            int iCount = 0;
            if ((vRootElement != null) && (vRootList != null))
            {
                XmlDocument myDoc = vRootElement.OwnerDocument;
                XmlElement NewElement = null;
                if ((vRootList.ChildNodes != null) && (vRootList.ChildNodes.Count > 0))
                {
                    foreach (KB_List myList in vRootList.ChildNodes)
                    {
                        NewElement = myDoc.CreateElement("kb");
                        vRootElement.AppendChild(NewElement);
                        myList.ToXML(NewElement);
                        iCount++;
                        iCount += this.KBListToXML(NewElement, myList, IncludeTemplate, myCmd);
                        if (this.myKBSectionList != null)
                        {
                            StringBuilder myStr = new StringBuilder();
                            bool bolFirst = true;
                            foreach (KBSection mySection in this.myKBSectionList)
                            {
                                if (mySection.KBSEQ == myList.SEQ)
                                {
                                    myStr.Append(mySection.OwnerSection);
                                    if (!bolFirst)
                                    {
                                        myStr.Append(",");
                                    }
                                    bolFirst = false;
                                }
                            }
                            if (myStr.Length > 0)
                            {
                                NewElement.SetAttribute("bindsection", myStr.ToString());
                            }
                        }
                    }
                    return iCount;
                }
                if ((vRootList.Items == null) || (vRootList.Items.Count <= 0))
                {
                    return iCount;
                }
                foreach (KB_Item myItem in vRootList.Items)
                {
                    NewElement = myDoc.CreateElement("item");
                    vRootElement.AppendChild(NewElement);
                    myItem.ToXML(NewElement);
                    iCount++;
                    if ((myItem.isTemplate() && StringCommon.IsInteger(myItem.ItemValue)) && (IncludeTemplate && (myCmd != null)))
                    {
                        try
                        {
                            myCmd.CommandText = "Select ObjectData From ET_Document Where ObjectID = " + myItem.ItemValue;
                            IDataReader myReader = myCmd.ExecuteReader(CommandBehavior.SingleRow | CommandBehavior.SingleResult);
                            string strData = null;
                            if (myReader.Read())
                            {
                                strData = myReader.GetString(0);
                            }
                            myReader.Close();
                            if (strData != null)
                            {
                                XmlDocument myTmpDoc = new XmlDocument();
                                myTmpDoc.LoadXml(strData);
                                XmlNode myXMLNode = myDoc.ImportNode(myTmpDoc.DocumentElement, true);
                                NewElement.AppendChild(myXMLNode);
                            }
                            continue;
                        }
                        catch (Exception ext)
                        {
                            MessageBox.Show(null, "导出模板 " + myItem.ItemText + " 数据错误:\r\n" + ext.ToString() + myCmd.CommandText, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                            continue;
                        }
                    }
                }
            }
            return iCount;
        }

        public KB_List LoadAllKBList(bool FixListIndex)
        {
            ZYErrorReport.Instance.DebugPrint("开始加载知识库");
            if (this.myConn == null)
            {
                return null;
            }
         
            try
            {
                if (TrvSelectKBList.Nodes.Count > 0)
                {
                    TrvSelectKBList.Nodes.Clear();
                }

                if (this.myRootList.ChildNodes != null)
                {
                    this.myRootList.ChildNodes.Clear();
                }

                this.bolLoading = true;
                this.myRootList = new KB_List();
                this.myRootList.SEQ = null;
                this.myRootList.OwnerSection = null;
                if (StringCommon.isBlankString(this.strOwnerSection))
                {
                    this.strOwnerSection = null;
                }
                else
                {
                    this.strOwnerSection = this.strOwnerSection.Trim();
                }
                this.myAllKBList = new ArrayList();
                ArrayList myItemList = new ArrayList();
                using (IDbCommand myCmd = this.myConn.CreateCommand())
                {
                    this.myAllKBList = new ArrayList();
                    if (this.LoadRecords(this.myAllKBList, 0, myCmd) == -1)
                    {
                        return null;
                    }
                    myItemList = new ArrayList();
                    if (this.LoadRecords(myItemList, 1, myCmd) == -1)//调试问题：应该在此部运行结束myItemList中就有值
                    {
                        return null;
                    }
                    if ((!this.DesignMode && this.bolEnableKBSection) && (this.strOwnerSection != null))
                    {
                        ArrayList myKSList = new ArrayList();
                        if (this.LoadRecords(myKSList, 4, myCmd) == -1)
                        {
                            return null;
                        }
                        foreach (KB_List myKL in this.myAllKBList)
                        {
                            bool bolMatch = false;
                            foreach (KBSection myKS in myKSList)
                            {
                                if (myKS.KBSEQ == myKL.SEQ)
                                {
                                    bolMatch = true;
                                }
                            }
                            myKL.Visible = bolMatch;
                        }
                    }
                }
                this.myConn.ExecuteCompleted();
                this.myRootList.Visible = true;
                this.StructAllKBList(this.myRootList, this.myAllKBList, myItemList, FixListIndex);
                this.RefreshKBChineseSpell();
                this.LoadKBRefCount();
                this.bolLoading = false;
                TreeNode tn = new TreeNode();
                GetAllList(myRootList.ChildNodes, myItemList, tn);
                for (int i = 0; i < tn.Nodes.Count; i++)
                {
                    TrvSelectKBList.Nodes.Add((TreeNode)tn.Nodes[i].Clone());
                }
                return this.myRootList;
            }
            catch (Exception ext)
            {
                ext.ToString();
                ZYErrorReport.Instance.DebugPrint("加载知识库错误:" + ext.ToString());
                ZYErrorReport.Instance.MemberName = "ZYKBBuffer.LoadAllKBList( bool )";
                ZYErrorReport.Instance.UserMessage = "加载知识库错误";
                ZYErrorReport.Instance.SourceException = ext;
                ZYErrorReport.Instance.SourceObject = this.myConn;
                ZYErrorReport.Instance.ReportError();
                return null;
            }
            finally
            {
                GC.Collect();
            }
        }

        private void GetAllList(ArrayList al, ArrayList items, TreeNode trv)
        {
            for (int i = 0; i < al.Count; i++)
            {
                TreeNode tn = new TreeNode();
                tn.Tag = al[i];
                if (al[i].GetType().ToString().Contains("KB_List"))
                {
                    KB_List temp = (KB_List)al[i];
                    tn.Text = temp.Name;
                    //tn.ImageIndex = 0;
                    if (temp.Islist == 0)
                    {
                        tn.ImageIndex=0;
                        tn.SelectedImageIndex=1;
                    }
                    else
                    {
                        tn.ImageIndex=2;
                        tn.SelectedImageIndex=3;
                    }

                    if (temp.ChildNodes != null)
                    {
                        if (temp.ChildNodes.Count > 0)
                        {
                            GetAllList(temp.ChildNodes, items, tn);
                        }
                    }
                    else
                    {
                        for (int i1 = 0; i1 < items.Count; i1++)
                        {
                            if (items[i].GetType().ToString().Contains("KB_Item"))
                            {

                                KB_Item temp2 = (KB_Item)items[i1];
                                if (temp2.KBSEQ != null)
                                {
                                    if (temp.SEQ.Trim() == temp2.KBSEQ.Trim())
                                    {
                                        //TreeNode tn2 = new TreeNode();
                                        //tn2.Text = temp2.ItemText;
                                        //tn2.Tag = temp2;
                                        //tn2.ImageIndex = 1;
                                        //tn.Nodes.Add(tn2);

                                        TreeNode node2 = new TreeNode();
                                        node2.Text = temp2.ItemText;
                                        node2.Tag = temp2 ;
                                        if (temp2.ItemStyle == 100)
                                        {
                                            node2.ImageIndex = 5;
                                            node2.SelectedImageIndex = 5;
                                        }
                                        else
                                        {
                                            node2.ImageIndex = 4;
                                            node2.SelectedImageIndex = 4;
                                        }
                                        tn.Nodes.Add(node2);
                                    }
                                }
                            }
                        }
                    }
                }
                trv.Nodes.Add(tn);
            }
        }

        public KB_List LoadAllKBList(XmlElement RootElement, bool FixListIndex)
        {
            this.bolLoading = true;
            this.myRootList = new KB_List();
            this.myRootList.OwnerSection = null;
            this.myRootList.SEQ = null;
            this.myAllKBList = new ArrayList();
            ArrayList myItemList = new ArrayList();
            foreach (XmlNode myXMLNode in RootElement.ChildNodes)
            {
                if (myXMLNode.Name == "list")
                {
                    KB_List NewList = new KB_List();
                    NewList.FromXML((XmlElement) myXMLNode);
                    NewList.DataState = DataRowState.Unchanged;
                    if (NewList.SEQ != null)
                    {
                        this.myAllKBList.Add(NewList);
                    }
                }
                if (myXMLNode.Name == "item")
                {
                    KB_Item NewItem = new KB_Item();
                    NewItem.FromXML((XmlElement) myXMLNode);
                    NewItem.DataState = DataRowState.Unchanged;
                    myItemList.Add(NewItem);
                }
            }
            this.StructAllKBList(this.myRootList, this.myAllKBList, myItemList, FixListIndex);
            this.RefreshKBChineseSpell();
            this.bolLoading = false;
            return this.myRootList;
        }

        public int[] LoadAllKBSEQ()
        {
            using (IDbCommand myCmd = this.myConn.CreateCommand())
            {
                Int32Buffer myBuffer = new Int32Buffer();
                KB_List.SetSelectSEQCommand(myCmd);
                IDataReader myReader = myCmd.ExecuteReader(CommandBehavior.SingleResult);
                while (myReader.Read())
                {
                    myBuffer.Append(Convert.ToInt32(myReader[0]));
                }
                myReader.Close();
                return myBuffer.ToArray();
            }
        }

        private void LoadKBRefCount()
        {
            if ((this.myAllKBList != null) && (this.myAllKBList.Count != 0))
            {
                try
                {
                    string strFile = Path.Combine(Application.StartupPath, "kbrefcount.dat");
                    if (File.Exists(strFile))
                    {
                        FileInfo myInfo = new FileInfo(strFile);
                        if ((myInfo.Length % 4L) == 0L)
                        {
                            FileStream myFile = new FileStream(strFile, FileMode.Open, FileAccess.Read);
                            byte[] bytBuffer = new byte[myFile.Length];
                            myFile.Read(bytBuffer, 0, bytBuffer.Length);
                            myFile.Close();
                            for (int iCount = 0; iCount < bytBuffer.Length; iCount += 4)
                            {
                                if (iCount >= this.myAllKBList.Count)
                                {
                                    return;
                                }
                                int RefCount = BitConverter.ToInt32(bytBuffer, iCount) % 0x100;
                                if (RefCount < 0)
                                {
                                    RefCount = 0;
                                }
                                ((KB_List) this.myAllKBList[iCount]).RefCount = RefCount;
                            }
                        }
                    }
                }
                catch
                {
                }
            }
        }

        public void LoadKBSection()
        {
            if (this.bolEnableKBSection && (this.myConn != null))
            {
                if (this.myKBSectionList != null)
                {
                    this.myKBSectionList.Clear();
                }
                this.myKBSectionList = this.myConn.ReadAllRecords(new KBSection());
            }
        }

        //加载查询出来的数据
        public int LoadRecords(ArrayList myList, int Style, IDbCommand myCmd)
        {
            int iCount = -1;
            //myCmd.Parameters.Clear();myCmd.CommandText
            string Sql = "";
            switch (Style)
            {
                case 0:
                    if ((Custom_KBLIST_SQL == null) || (Custom_KBLIST_SQL.Length <= 0))
                    {
                        Sql = KB_List.GetSelectSQL() + " Order by ParentId ";//设置sql查询语句  Where OWNERSECTION = '" + this.strKeyPreFix + "'
                        break;
                    }
                    Sql = Custom_KBLIST_SQL;
                    break;

                case 1:
                    if ((Custom_KBITEM_SQL == null) || (Custom_KBITEM_SQL.Length <= 0))
                    {
                        Sql = KB_Item.GetSelectSQL();//+ "  Order by ParentId  ";//Where OWNERSECTION = '" + this.strKeyPreFix + "'
                    }
                    else
                    {
                        Sql = Custom_KBITEM_SQL;
                    }
                    //return this.myConn.ReadRecords(myList, new KB_Item(), myCmd);
                    return this.myConn.ReadRecords(myList, new KB_Item(), Sql);

                //case 2:
                //    myCmd.CommandText = KBSection.GetSelectSQL(); //+ " Where OWNERSECTION = '" + this.strKeyPreFix + "'";
                //    ZYDBConnection.AddParameter(myCmd, this.strOwnerSection);
                //    return this.myConn.ReadRecords(myList, new KBSection(), myCmd);

                //case 3:
                //    myCmd.CommandText = ET_Document.GetSelectSQL();// +" Where OWNERSECTION = '" + this.strKeyPreFix + "'";
                //    return this.myConn.ReadRecords(myList, new ET_Document(), myCmd);

                //case 4:
                //    myCmd.CommandText = KBSection.GetSelectSQL();// +" Where OWNERSECTION = '" + this.strKeyPreFix + "'";
                //    return this.myConn.ReadRecords(myList, new KBSection(), myCmd);

                default:
                    return iCount;
            }
            return this.myConn.ReadRecords(myList, new KB_List(), Sql);
        }

        public void RefreshAllKBList()
        {
            ZYDBRecordBase.RemoveDeletedRecord(this.myAllKBList, true);
            foreach (KB_List myList in this.myAllKBList)
            {
                ZYDBRecordBase.RemoveDeletedRecord(myList.ChildNodes, true);
                ZYDBRecordBase.RemoveDeletedRecord(myList.Items, true);
            }
            ZYDBRecordBase.RemoveDeletedRecord(this.myKBSectionList, true);
            this.myAllKBList.Clear();
            this.myTemplateList.Clear();
            this.RefreshAllKBList(this.myRootList);
            this.RefreshKBChineseSpell();
        }

        public void RefreshAllKBList(KB_List vRootList)
        {
            this.myAllKBList.Add(vRootList);
            if ((vRootList.ChildNodes != null) && (vRootList.ChildNodes.Count > 0))
            {
                foreach (KB_List myList in vRootList.ChildNodes)
                {
                    this.RefreshAllKBList(myList);
                }
            }
            if ((vRootList.Items != null) && (vRootList.Items.Count > 0))
            {
                foreach (KB_Item myItem in vRootList.Items)
                {
                    if (myItem.isTemplate())
                    {
                        this.myTemplateList.Add(myItem);
                    }
                }
            }
        }

        private void RefreshKBChineseSpell()
        {
            foreach (KB_List myList in this.myAllKBList)
            {
                myList.ChineseSpell = StringCommon.GetChineseSpell(myList.Name);
            }
        }

        //
        private void SaveKBRefCount()
        {
            if ((this.myAllKBList != null) && (this.myAllKBList.Count != 0))
            {
                try
                {
                    string strFile = Path.Combine(Application.StartupPath, "kbrefcount.dat");
                    if (File.Exists(strFile))
                    {
                        File.SetAttributes(strFile, FileAttributes.Normal);
                    }
                    FileStream myFile = new FileStream(strFile, FileMode.Create, FileAccess.Write);
                    foreach (KB_List myKBList in this.myAllKBList)
                    {
                        myFile.Write(BitConverter.GetBytes(myKBList.RefCount), 0, 4);
                    }
                    myFile.Close();
                }
                catch
                {
                }
            }
        }

        private void StructAllKBList(KB_List vRootList, ArrayList myKBList, ArrayList myItemList, bool FixListIndex)
        {
            int i = 0;
            if ((vRootList != null) && (myKBList != null))
            {
                vRootList.SEQ = this.strKeyPreFix;//+ "0000000";//***************
                vRootList.Name = "知识库";
                vRootList.ChildNodes = new ArrayList();
                vRootList.Items = new ArrayList();
                vRootList.DataState = DataRowState.Unchanged;
                KB_List Parent = vRootList;
                foreach (KB_List myItem in myKBList)
                {
                    if (Parent.SEQ != myItem.ParentSEQ)
                    {
                        Parent = null;
                        foreach (KB_List myItem2 in this.myAllKBList)
                        {
                            i++;
                            if (myItem2.SEQ == myItem.ParentSEQ)
                            {
                                Parent = myItem2;
                                if (Parent.ChildNodes == null)
                                {
                                    Parent.ChildNodes = new ArrayList();
                                }
                                goto Label_00E0;
                            }
                        }
                    }
                    Label_00E0:
                    if (Parent != null)
                    {
                        Parent.ChildNodes.Add(myItem);
                        myItem.Parent = Parent;
                    }
                    else
                    {
                        Parent = vRootList;
                    }
                }
                if (myKBList.Contains(vRootList))
                {
                    myKBList.Remove(vRootList);
                }
                myKBList.Insert(0, vRootList);
                if (myItemList != null)
                {
                    this.myTemplateList = new ArrayList();
                    KB_Item myKBItem = new KB_Item();
                    Parent = vRootList;
                    foreach (KB_Item myItem in myItemList)
                    {
                        if (myItem.isTemplate())
                        {
                            this.myTemplateList.Add(myItem);
                        }
                        if (StringCommon.isBlankString(myItem.ItemValue))
                        {
                            myItem.ItemValue = myItem.ItemText;
                        }
                        if ((Parent == null) || (Parent.SEQ != myItem.KBSEQ))
                        {
                            Parent = null;
                            foreach (KB_List myItem2 in this.myAllKBList)
                            {
                                i++;
                                if (myItem2.SEQ == myItem.KBSEQ)
                                {
                                    Parent = myItem2;
                                    if (Parent.Items == null)
                                    {
                                        Parent.Items = new ArrayList();
                                    }
                                    //goto Label_0220;
                                    break;
                                }
                            }
                        }
                        //Label_0220:
                        if (Parent != null)
                        {
                            Parent.Items.Add(myItem);
                            myItem.OwnerList = Parent;
                        }
                        myItem.DataState = DataRowState.Unchanged;
                    }
                }
                if (FixListIndex)
                {              
                    foreach (KB_List myList in myKBList)
                    {
                        //由于现在编辑器不对数据库进行修改 所以ListIndex作用不在，但是是否更改过知识库又是根据ListIndex判断所以注释下面的判断代码
                        //int ListIndex = 0;
                        if ((myList.ChildNodes != null) && (myList.ChildNodes.Count > 0))
                        {
                            //foreach (KB_List myChild in myList.ChildNodes)
                            //{
                            //    if (myChild.ListIndex < ListIndex)
                            //    {
                            //        myChild.ListIndex = ListIndex;
                            //    }
                            //    ListIndex = myChild.ListIndex + 1;
                            //}
                        }
                        if ((myList.Items != null) && (myList.Items.Count > 0))
                        {
                            //ListIndex = 0;
                            //foreach (KB_Item myItem in myList.Items)
                            //{
                            //    if (myItem.ListIndex < ListIndex)
                            //    {
                            //        myItem.ListIndex = ListIndex;
                            //    }
                            //    ListIndex = myItem.ListIndex + 1;
                            //}                           
                        }
                    }
                }
                foreach (KB_List myList in myKBList)
                {
                    if ((myList.Items != null) && (myList.Items.Count == 0))
                    {
                        myList.Items = null;
                    }
                    if ((myList.ChildNodes != null) && (myList.ChildNodes.Count == 0))
                    {
                        myList.ChildNodes = null;
                    }
                    if (myList.ChildNodes != null)
                    {
                        myList.Items = null;
                    }
                }
            }
        }

        public int UniteKB(ArrayList myObjList, ObjectProgressHandler setStatus)
        {
            int ObjectCount = 0;
            using (IDbCommand myCmd = this.myConn.CreateCommand())
            {
                KB_List.SetSelectSEQCommand(myCmd);
                int[] KBSEQ = ZYDBConnection.GetInt32ValueList(myCmd);
                ET_Document.SetSelectSEQCommand(myCmd);
                int[] TempID = ZYDBConnection.GetInt32ValueList(myCmd);
                StringBuffer KBSEQBuffer = new StringBuffer();
                ArrayList SectionList = new ArrayList();
                int RecordCount = 0;
                foreach (object obj in myObjList)
                {
                    if (obj is KB_List)
                    {
                        ObjectCount++;
                        KB_List myKBList = (KB_List) obj;
                        KBSEQBuffer.Append(myKBList.SEQ);
                        if ((myKBList.Items != null) && (myKBList.Items.Count > 0))
                        {
                            foreach (KB_Item myItem in myKBList.Items)
                            {
                                myItem.SetInsertCommnad(myCmd, this.myConn);
                                myCmd.ExecuteNonQuery();
                            }
                        }
                        if (setStatus != null)
                        {
                            setStatus(obj, RecordCount, myObjList.Count);
                        }
                    }
                    if (obj is ET_Document)
                    {
                        ObjectCount++;
                        ET_Document myDoc = (ET_Document) obj;
                        myCmd.ExecuteNonQuery();
                        if (setStatus != null)
                        {
                            setStatus(obj, RecordCount, myObjList.Count);
                        }
                    }
                    if (obj is KBSection)
                    {
                        ObjectCount++;
                        SectionList.Add(obj);
                        if (setStatus != null)
                        {
                            setStatus(obj, RecordCount, myObjList.Count);
                        }
                    }
                    RecordCount++;
                }
                if (setStatus != null)
                {
                    setStatus("正在更新科室绑定信息...", myObjList.Count, myObjList.Count);
                }
                if (KBSEQBuffer.Count > 0)
                {
                    myCmd.CommandText = "Delete From KBSection Where KB_SEQ in (" + KBSEQBuffer.ToStringList(',') + ")";
                    myCmd.ExecuteNonQuery();
                }
                foreach (KBSection mySection in SectionList)
                {
                    mySection.SetInsertCommnad(myCmd, this.myConn);
                    myCmd.ExecuteNonQuery();
                }
                return ObjectCount;
            }
        }

        public int UpdateDataBase(ArrayList myRecords, ProgressHandler p)
        {
            SEQCreator mySEQ = new SEQCreator();
            SEQCreator myDocSEQ = new SEQCreator();
            mySEQ.FixLength = 10;
            int intKBItemSEQ = 1;
            using (IDbCommand myCmd = this.myConn.CreateCommand())
            {
                mySEQ.SEQ = this.GetSEQString("Select Max(KB_SEQ) From KB_List Where OWNERSECTION='" + this.strOwnerSection + "'", myCmd);
                myDocSEQ.SEQ = this.GetSEQString("Select Max(ObjectID) From ET_Document Where OWNERSECTION='" + this.strOwnerSection + "'", myCmd);
                intKBItemSEQ = Convert.ToInt32(this.myConn.GetSingleValue("Select Max(Item_SEQ)+1 From KB_Item"));
            }
            foreach (ZYDBRecordBase myRecord in myRecords)
            {
                if (!myRecord.isKeyEnable() && myRecord.isNewRecord())
                {
                    if (myRecord is KB_List)
                    {
                        myRecord.SetKeyWord(mySEQ.Create());
                    }
                    else
                    {
                        if (myRecord is KB_Item)
                        {
                            myRecord.SetKeyWord(intKBItemSEQ.ToString());
                            intKBItemSEQ++;
                            continue;
                        }
                        myRecord.SetKeyWord(myDocSEQ.Create());
                    }
                }
            }
            return this.myConn.UpdateRecords(myRecords, p);
        }

        public int UpdateEMR(string strXMLFileName, ZYDBConnection myConn, bool CanUpdate, ObjectProgressHandler setStatus)
        {
            if (((!StringCommon.isBlankString(strXMLFileName) && (myConn != null)) && (myConn.isOpened() && (this.myAllKBList != null))) && (this.myAllKBList.Count > 0))
            {
                int iRecordCount = 0;
                string strSQL = "Select ElementName From ERMSECTIONCOMPOSEINFO Where ErmxslFileName = '" + strXMLFileName + "'";
                string[] strNameList = myConn.GetValueList(strSQL);
                using (IDbCommand InsertCmd = myConn.CreateCommand())
                {
                    using (IDbCommand UpdateCmd = myConn.CreateCommand())
                    {
                        InsertCmd.CommandText = "Insert Into ERMSECTIONCOMPOSEINFO (ERMXSLFILENAME,ELEMENTDESC , ELEMENTNAME, MULTIVALUEFLAG,AIDFLAG) Values('" + strXMLFileName + "', ? , ? , '0' , '2')";
                        InsertCmd.Parameters.Add(InsertCmd.CreateParameter());
                        InsertCmd.Parameters.Add(InsertCmd.CreateParameter());
                        if (CanUpdate)
                        {
                            UpdateCmd.CommandText = "Update ERMSECTIONCOMPOSEINFO Set ELEMENTDESC = ? Where ELEMENTNAME = ? And  ERMXSLFILENAME='" + strXMLFileName + "'";
                            UpdateCmd.Parameters.Add(InsertCmd.CreateParameter());
                            UpdateCmd.Parameters.Add(InsertCmd.CreateParameter());
                        }
                        bool bolMatch = false;
                        foreach (KB_List myList in this.myAllKBList)
                        {
                            if (myList.SEQ == null)
                            {
                                continue;
                            }
                            string strElementName = "kb" + myList.SEQ.ToString();
                            bolMatch = false;
                            if (strNameList != null)
                            {
                                foreach (string strName in strNameList)
                                {
                                    if ((strName != null) && strName.Equals(strElementName))
                                    {
                                        bolMatch = true;
                                        break;
                                    }
                                }
                            }
                            int intProgress = (iRecordCount * 100) / this.myAllKBList.Count;
                            if (bolMatch)
                            {
                                if (CanUpdate)
                                {
                                    if (setStatus != null)
                                    {
                                        setStatus(myList, iRecordCount, this.myAllKBList.Count);
                                    }
                                    (UpdateCmd.Parameters[0] as IDataParameter).Value = myList.Name;
                                    (UpdateCmd.Parameters[1] as IDataParameter).Value = strElementName;
                                    UpdateCmd.ExecuteNonQuery();
                                }
                            }
                            else
                            {
                                if (setStatus != null)
                                {
                                    setStatus(myList, iRecordCount, this.myAllKBList.Count);
                                }
                                (InsertCmd.Parameters[0] as IDataParameter).Value = myList.Name;
                                (InsertCmd.Parameters[1] as IDataParameter).Value = strElementName;
                                InsertCmd.ExecuteNonQuery();
                            }
                            iRecordCount++;
                        }
                        return iRecordCount;
                    }
                }
            }
            return -1;
        }

        public void UpdateSectionList()
        {
            this.SectionList = this.myConn.GetValueList(this.SectionSQL, false, false);
        }

        public ArrayList AllKBList
        {
            get
            {
                return this.myAllKBList;
            }
        }

        public ZYDBConnection Connection
        {
            get
            {
                return this.myConn;
            }
            set
            {
                this.myConn = value;
            }
        }

        public bool EnableKBSection
        {
            get
            {
                return this.bolEnableKBSection;
            }
            set
            {
                this.bolEnableKBSection = value;
            }
        }

        public static ZYKBBuffer Instance
        {
            get
            {
                return myInstance;
            }
        }

        public ArrayList KBSectionList
        {
            get
            {
                return this.myKBSectionList;
            }
        }

        public string KeyPreFix
        {
            get
            {
                return this.strKeyPreFix;
            }
            set
            {
                this.strKeyPreFix = value;
            }
        }

        public bool Loading
        {
            get
            {
                return this.bolLoading;
            }
            set
            {
                this.bolLoading = value;
            }
        }

        public string OwnerSection
        {
            get
            {
                return this.strOwnerSection;
            }
            set
            {
                this.strOwnerSection = value;
            }
        }

        public KB_List RootList
        {
            get
            {
                return this.myRootList;
            }
        }

        public ArrayList TemplateList
        {
            get
            {
                return this.myTemplateList;
            }
        }
    }
}

